<template>
    <div id="mapBoxId"></div>
    <div class="option-btn__list">
        <button class="btn-item" @click="start">坐标拾取</button>
        <button class="btn-item" @click="clear">清除</button>
    </div>
</template>
<script lang="ts" setup>
import { TDMAP_TK } from '@/utils/constant';
import { Feature, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import { fromLonLat } from 'ol/proj';
import { XYZ } from 'ol/source';
import MapType from 'ol/Map.js';
import { defaults as defaultControls } from 'ol/control';
import { Point } from 'ol/geom';
import Style from 'ol/style/Style';
import Icon from 'ol/style/Icon';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Circle from 'ol/style/Circle';
import Text from 'ol/style/Text';
import markersd from '@/assets/img/markersd.png';
let map: MapType;
let markerLayer: any;

/**
 * 图层
 */
const getLayers = () => {
    // 天地图矢量图层
    const tdMapVectorLayer = new TileLayer({
        zIndex: 30,
        className: 'tdVector',
        visible: true,
        source: new XYZ({
            url: `https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${TDMAP_TK}`,
            wrapX: false
        })
    });
    // 天地图标注层
    const tdMapCvaLayer = new TileLayer({
        zIndex: 31,
        className: 'tdCva',
        visible: true,
        source: new XYZ({
            url: `https://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=${TDMAP_TK}`,
            wrapX: false
        })
    });
    const layers = [tdMapVectorLayer, tdMapCvaLayer];
    return layers;
};
/**
 * 初始化地图
 */
const initMap = () => {
    const layers = getLayers();
    const view = new View({
        center: fromLonLat([86.25903, 41.33632]),
        zoom: 16,
        minZoom: 9,
        maxZoom: 18,
        constrainResolution: true, // 设置缩放级别为整数
        smoothResolutionConstraint: false // 关闭无级缩放地图
    });
    map = new MapType({
        target: 'mapBoxId',
        layers,
        view,
        controls: defaultControls({
            zoom: false,
            rotate: false,
            attribution: false
        })
    });
};

const start = () => {
    const dom = document.getElementById('mapBoxId');
    if (!dom) return;
    // 设置测距的图层
    const source = new VectorSource();
    markerLayer = new VectorLayer({
        source: source,
        style: new Style({
            fill: new Fill({
                //填充颜色
                color: 'rgba(37,241,239,0.2)'
            }),
            stroke: new Stroke({
                color: '#FF0000',
                width: 4
            }),

            image: new Circle({
                radius: 5,
                stroke: new Stroke({
                    color: '#FF0000', //边框颜色
                    width: 3
                }),
                fill: new Fill({
                    color: '#ffffff' //填充颜色
                })
            })
        }),
        zIndex: 32
    });
    map.addLayer(markerLayer);
    dom.style.cursor = 'crosshair';
    map.on('click', function (evt) {
        const param = {
            style: {
                text: `经度: ${evt.coordinate[0].toFixed(4)}\n纬度: ${evt.coordinate[1].toFixed(4)}`,
                offsetY: 35
            },
            geometry: evt.coordinate
        };
        addLabel(param);
    });
    const addLabel = (param: any) => {
        markerLayer.getSource()?.clear();
        const feature = new Feature({
            geometry: new Point(param.geometry)
        });
        const style = new Style({
            image: new Icon({
                src: markersd
            }),
            text: new Text({
                //位置
                textAlign: 'center',
                //基准线
                textBaseline: 'middle',
                //文字样式
                font: 'normal 14px 微软雅黑',
                offsetX: 0,
                offsetY: param.style.offsetY ? param.style.offsetY : 25,
                //文本内容
                text: param.style.text ? param.style.text : '',
                //文本填充样式（即文字颜色）
                fill: new Fill({ color: 'blue' })
                // stroke: new Stroke({ color: 'rgba(255, 255, 255)'})
            })
        });
        feature.setStyle(style);
        markerLayer.getSource()?.addFeature(feature);
    };
};
const clear = () => {
    map.removeLayer(markerLayer);
    const dom = document.getElementById('mapBoxId');
    if (!dom) return;
    dom.style.cursor = 'default';
};

/**
 * 销毁左侧地图
 */
const distoryMap = () => {
    map && map.setTarget();
    map && map.dispose();
};
onMounted(() => {
    initMap();
});
onBeforeUnmount(() => {
    distoryMap();
});
</script>
<style lang="scss" scoped>
#mapBoxId {
    width: 100vw;
    height: 100vh;
}
.option-btn__list {
    position: fixed;
    right: 20px;
    top: 20px;
    display: flex;
    z-index: 99;
    gap: 10px;
    .btn-item {
        border: none;
        background-color: #1e71ff;
        border-radius: 20px;
        padding: 0 20px;
        text-align: center;
        color: #fff;
        height: 36px;
        line-height: 36px;
        cursor: pointer;
    }
}
</style>
